/**
 * 
 * BluetoothScan.start("",function(res){
 * 
 *    console.log("返回",res);
 * 
 * })
 * 
 * 本方法为扫描附近的设备..返回所有设备并按照信号的从强到弱进行排序进行排序
 * 
 */


var BluetoothSortingScan = {};
var deviceArray = [];

BluetoothSortingScan.distance = ((rssi, A, n) => {
  let iRssi = Math.abs(rssi);
  let power = (iRssi - A) / (10 * n);
  return Math.pow(10, power);
}),
  //蓝牙开始 更改后
  BluetoothSortingScan.start = function (that, callback) {
    console.log('蓝牙开始');
    var self = this
    deviceArray = [];
    //切断所有蓝牙
    wx.closeBluetoothAdapter({
      success: function (res) {
        //打开蓝牙
        wx.openBluetoothAdapter({
          success: function (res) {

            wx.getBluetoothAdapterState({
              success: function (res) { }
            })
            wx.onBluetoothAdapterStateChange(function (res) {
              if (!res.available) { }
            })
            wx.onBluetoothDeviceFound(function (res) {
              //剔除重复设备，兼容不同设备API的不同返回值
              var isnotexist = true
              if (res.devices[0]) {
                var deviceName = res.devices[0].localName;
                var rssi = res.devices[0].RSSI;
                let device = {
                  "name": deviceName,
                  "rssi": rssi,
                  "deviceId": res.devices[0].deviceId
                };
                deviceArray.push(device);
              }
            })
            wx.startBluetoothDevicesDiscovery({
              services: ['6E400001-B5A3-F393-E0A9-E50E24DCCA9E', '0000FEE8-0000-1000-8000-00805F9B34FB', '0000FEC9-0000-1000-8000-00805F9B34FB', '0000FEC7-0000-1000-8000-00805F9B34FB', "FFE0", "FFF0", "CB01", "CB02"],
              allowDuplicatesKey: false,
              success: function (res) {
                setTimeout(() => {
                  self.stop(callback); //延时停止扫描
                }, 1000)
              },
              fail() {
                self.stop(callback);
              }
            })
          },
          fail: function (res) {
            wx.showModal({
              title: '提示',
              content: '请检查手机蓝牙是否打开',
              showCancel: false,
              success: function (res) { }
            })
          }
        })
      }
    })
  }

BluetoothSortingScan.stop = function (callback) {

  setTimeout(function () {
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("停止扫描");
        deviceArray = deviceArray.sort(function (a, b) {
          return b.rssi - a.rssi //如果是降序，则为b - a
        })
        callback(deviceArray);
      }
    })
  }, 500);

}

module.exports = BluetoothSortingScan;